export const u = navigator.userAgent;
export const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; // android终端
export const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
export const isDDWin = u.indexOf('dingtalk-win') > -1 && u.downloadFile('uos') == -1;

/*
 * @param {string, string} date, fmt
 * @Description:  对Date的扩展，将 Date 转化为指定格式的String
 *                月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 *                (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 *                (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
 * @return: string
*/
export function DateFormat(date, fmt) { // author: meizz
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  };
  // eslint-disable-next-line
  if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (`${date.getFullYear()}`).substr(4 - RegExp.$1.length)); }
  // eslint-disable-next-line
  for (const k in o) {
    // eslint-disable-next-line
    if (new RegExp(`(${k})`).test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : ((`00${o[k]}`).substr((`${o[k]}`).length))); }
  }
  return fmt;
}
/*
 * @param {}
 * @Description: 判断是否PC端
*/
export const IsPC = () => {
  const userAgentInfo = navigator.userAgent;
  const Agents = ['Android', 'iPhone',
    'SymbianOS', 'Windows Phone',
    'iPad', 'iPod'];
  let flag = true;
  for (let v = 0; v < Agents.length; v += 1) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false;
      break;
    }
  }
  return flag;
};
/*
 * @Description: 是否微信
*/
export const IsWechat = () => {
  const ua = window.navigator.userAgent.toLowerCase();
  return ua.match(/MicroMessenger/i) == 'micromessenger';
};

/*
 * @Description: 判断字符长度
*/
export const Strlen = (str) => {
  let len = 0;
  for (let i = 0; i < str.length; i += 1) {
    const c = str.charCodeAt(i);
    // 单字节加1
    if ((c >= 0x0001 && c <= 0x007e) || (c >= 0xff60 && c <= 0xff9f)) {
      len += 1;
    } else {
      len += 2;
    }
  }
  return len;
};
/*
 * @Description: 获取URL后缀
*/
export const GetQuery = (key) => {
  let after = window.location.search;
  after = after.substr(1) || window.location.hash.split('?')[1];
  if (after) {
    const reg = new RegExp(`(^|&)${key}=([^&]*)(&|$)`);
    const r = after.match(reg);
    if (r != null) {
      return (r[2]);
    }
    return null;
  }
  return null;
};

/**
 * @des: 身份证验证
*/
/* eslint-disable */
export function validateIdCard (idCard) {
    var flag = false
    // 15位和18位身份证号码的正则表达式
    var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/

    // 如果通过该验证，说明身份证格式正确，但准确性还需计算
    if (regIdCard.test(idCard)) {
        if (idCard.length == 18) {
            var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2) // 将前17位加权因子保存在数组里
            var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2) // 这是除以11后，可能产生的11位余数、验证码，也保存成数组
            var idCardWiSum = 0 // 用来保存前17位各自乖以加权因子后的总和
            for (var i = 0; i < 17; i++) {
                idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i]
            }

            var idCardMod = idCardWiSum % 11// 计算出校验码所在数组的位置
            var idCardLast = idCard.substring(17)// 得到最后一位身份证号码

            // 如果等于2，则说明校验码是10，身份证号码最后一位应该是X
            if (idCardMod == 2) {
                if (idCardLast == 'X' || idCardLast == 'x') {
                    flag = true
                } else {
                    flag = false
                }
            } else {
                // 用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                if (idCardLast == idCardY[idCardMod]) {
                    flag = true
                } else {
                    flag = false
                }
            }
        } else if (idCard.length == 15) {
            var id17 = idCard.substring(0, 6) + '19' + idCard.substring(6)
            var parityBit = getParityBit(id17)
            var tempIdCard = id17 + parityBit
            flag = validateIdCard(tempIdCard)
        }
     } else {
        flag = false
     }
     return flag
}

export function routerReset(d, order = 0) {
  d.forEach(m => {
    m.order = order;
    if(m.component) {
      const c = m.component;
      m.component = (resolve) => require(['@/views/' +c+'.vue'], resolve)
    }
    if(m.children && m.children.length) {
      routerReset(m.children, order + 1);
    }
  })
}

// export function routerAsync(d, folder,order = 0, routerId) {
//   d.forEach(m => {
//     if(m.taskId) {
//       routerId.push(m.taskId);
//     }
//     if(order != 0) {
//       const temp = JSON.parse(JSON.stringify(m));
//       m.order = order;
//       m.folder = folder;
      
//       if (!m.path) m.path = `/index/${folder}/${folder}${m.taskId}`;
//       if (!m.name) m.name = `${folder}${m.taskId}`;
//       if (!m.component) m.component = (resolve) => require(['@/views/enter/FutureFactoryStep1.vue'], resolve);
//       if (!m.meta) m.meta = {
//         hidden: order >= 3 ? 1 : 0,
//         title: m.taskName,
//         ...m,
//         tree: temp
//       }
//     }
//     if(m.children && m.children.length) {
//       m.children.push({
//         path: `/index/${folder}/detail${m.taskId}`,
//         name: `/index/${folder}/detail${m.taskId}`,
//         folder: folder,
//         component: (resolve) => require(['@/views/enter/Detail.vue'], resolve),
//         meta: {
//             hidden: 1
//         },
//       })
//       routerAsync(m.children, folder, order + 1, routerId);
//     } else {
//       m.children = [];
//       m.children.push({
//         path: `/index/${folder}/detail${m.taskId|| Math.random()*10000000+10000}`,
//         name: `/detail${m.taskId|| Math.random()*10000000+10000}`,
//         folder: folder,
//         component: (resolve) => require(['@/views/enter/Detail.vue'], resolve),
//         meta: {
//           hidden: 1
//         },
//       })
//     }
//   })
// }

// export function routerAsync(d, order = 0) {
//   d.forEach(m => {
//     if(order != 0) {
//       const temp = JSON.parse(JSON.stringify(m));
//       m.order = order;
      
//       m.path = `/index/annualSummary/annualSummary${m.taskId}`;
//       m.name = `annualSummary${m.taskId}`;
//       m.component = (resolve) => require(['@/views/enter/FutureFactoryStep1.vue'], resolve);
//       m.meta = {
//         hidden: order >= 3 ? 1 : 0,
//         title: m.taskName,
//         ...m,
//         tree: temp
//       }
//     }
//     if(m.children && m.children.length) {
//       routerAsync(m.children, order + 1);
//     }
//   })
// }
/**
 * des: 文件类型限制
 * @param {file, isImage}
 * @returns {*}
*/
export function isFile(file, isImage) {
  let reg = /\.(bmp|jpg|jpeg|png|doc|docx|pdf|xls|xlsx)$/;
  if (isImage) {
    reg = /\.(jpg|jpeg|png)$/;
  }
  return reg.test(file);
}
/**
 * des: 文件下载
 * @param {file, isImage}
 * @returns {*}
*/
export function downloadFile(url, fileName) {
  var x = new XMLHttpRequest();
    x.open('GET', url, true);
    x.responseType = 'blob';
    x.onload = function(e) {
      var url = window.URL.createObjectURL(x.response);
      var a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      a.click();
    };
    x.send();
}

export function replaceHTML(e) {
  return e.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, '').replace(/<[^>]+?>/g, '').replace(/\s+/g, ' ').replace(/ /g, ' ').replace(/>/g, ' ').replace(/&nbsp;/g, '').replace(/&rdquo;/g, '').replace(/&ldquo;/g, '');
}
